package com.tuanzi.loan.web.bean.family;

import static com.tuanzi.loan.business.constants.DictionaryCode.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;

import com.google.gson.Gson;
import com.tuanzi.loan.business.entity.CurrentUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.entity.family.ApiActivity;
import com.tuanzi.loan.business.entity.family.ContentActivity;
import com.tuanzi.loan.business.entity.family.ProductManyHeadInfo;
import com.tuanzi.loan.business.entity.family.ProductTongdunManyHead;
import com.tuanzi.loan.business.entity.product.prefilter.LoanProductPrefilter;
import com.tuanzi.loan.business.entity.settlement.CompanyInfo;
import com.tuanzi.loan.business.enums.RegionTreeEnum;
import com.tuanzi.loan.business.service.common.CommRegionNewService;
import com.tuanzi.loan.business.service.family.*;
import com.tuanzi.loan.business.service.product.prefilter.LoanProductPrefilterService;
import com.tuanzi.loan.business.service.settlement.CompanyInfoService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.view.family.product.ApplyCondition;
import com.tuanzi.loan.vo.view.family.product.ProductInfoView;
import com.tuanzi.loan.vo.view.family.product.ProductJoinedLimit;
import com.tuanzi.loan.web.configuration.JSFInfoBean;

import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * @author Ray 2017/09/21
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
@Slf4j
public class FirstPartyTagInfoBean extends JSFInfoBean<ProductInfoView> {

	private static final long serialVersionUID = -2152778554108785342L;
	@Autowired
	private ContentActivityService contentActivityService;
	@Autowired
	private ApiActivityService apiActivityService;
	@Autowired
	private ProductInfoService productInfoService;
	@Autowired
	private CommRegionNewService commRegionNewService;
	@Autowired
	private CompanyInfoService companyInfoService;
	@Autowired
	private ProductManyHeadInfoService productManyHeadInfoService;
	@Autowired
	private ProductTongdunManyHeadInfoService productTongdunManyHeadInfoService;
	@Autowired
	private LoanProductPrefilterService productPrefilterService;

	private List<ContentActivity> contentActivities;
	private List<ApiActivity> apiActivities;
	private TreeNode areaRegion;
	private TreeNode[] selectedRegionNodes;
	private List<CompanyInfo> companyList;
	private ProductManyHeadInfo manyHeadInfo;// 风控信息
	private List<ProductTongdunManyHead> tongdunManyHeads;// 同盾多头
	private ProductTongdunManyHead selectTongdunManyHead;// 同盾多头
	private List<String> tongdunIndustryList;
	private List<LoanProductPrefilter> loanProductPrefilters;

	public static void main(String[] args) {
		UUID uu = UUID.randomUUID();
		System.out.println(uu.toString());
	}

	@PostConstruct
	private void init() {
		String id = getParamFromRequest("id");
		if (StringUtils.isNotBlank(id)) {
			$ = productInfoService.loadProductInfoView(NumberUtils.toLong(id));
			// 魔杖查询风控信息
			manyHeadInfo = productManyHeadInfoService.findByActivityId(NumberUtils.toLong(id));
			if (manyHeadInfo == null) {
				manyHeadInfo = new ProductManyHeadInfo();
				manyHeadInfo.setActivityId(NumberUtils.toLong(id));
			}
			// 同盾多头
			tongdunManyHeads = productTongdunManyHeadInfoService.findByActivityId(NumberUtils.toLong(id));
			if (tongdunManyHeads == null) {
				tongdunManyHeads = new ArrayList<>();
			}

		} else {
			$ = new ProductInfoView();
			$.setIsAddReplace(0);// 默认不加入替补池
			manyHeadInfo = new ProductManyHeadInfo();

			$.setProductJoinedLimit(new ProductJoinedLimit());
			$.setOpenType(0);
			$.setRedirectType(1);
			ApplyCondition applyCondition = new ApplyCondition();
			applyCondition.setAreaCondition(new ApplyCondition.AreaCondition());
			applyCondition.setBasicCondition(new ApplyCondition.BasicCondition());
			applyCondition.setBlackListCondition(new ApplyCondition.BlackListCondition());
			applyCondition.setLongLoanCondition(new ApplyCondition.LongLoanCondition());
			$.setApplyCondition(applyCondition);

			tongdunManyHeads = new ArrayList<>();
			changeStatusToAdd();
		}

		loanProductPrefilters = productPrefilterService.findAll();
		contentActivities = contentActivityService.findAll();
		apiActivities = apiActivityService.findAll();
		areaRegion = commRegionNewService.generateTreeNode($.getFilterCity(), RegionTreeEnum.ALL);
		companyList = companyInfoService.findAllCompanyName();
		selectTongdunManyHead = new ProductTongdunManyHead();
		tongdunIndustryList = Lists.newArrayList();
	}

	public void onSave() {
		if (validate() == false){
			return;
		}
		$.getApplyCondition().getAreaCondition().setExcludeProvince(commRegionNewService.extractProvinceFrom($.getSelectedRegionNodes()));
		$.getApplyCondition().getAreaCondition().setExcludeCity(commRegionNewService.extractCityFrom($.getSelectedRegionNodes()));

		productInfoService.saveOrUpdateProductInfoView($, manyHeadInfo, tongdunManyHeads);
		changeStatusToView();
		addSuccessfullyMessage();
	}

	public boolean validate() {
		if (StringUtils.isBlank($.getPassRate())) {
			addErrorMessage("营销信息配置【审批通过率】为空");
			return false;
		}
		if (StringUtils.isBlank($.getLastweekPassRate())) {
			addErrorMessage("营销信息配置【上周审批通过率】为空");
			return false;
		}
		if (StringUtils.isBlank($.getPlatformScore())) {
			addErrorMessage("营销信息配置【平台综合评分】为空");
			return false;
		}
		if (StringUtils.isBlank($.getLendDate())) {
			addErrorMessage("营销信息配置【批款时间】为空");
			return false;
		}
		if ($.getSuccessCount() == null) {
			addErrorMessage("营销信息配置【成功申请人数】为空");
			return false;
		}
		if ($.getAveragePrice() == null) {
			addErrorMessage("基础信息配置【件均价】为空");
			return false;
		}

		if ($.getRateType() == null) {
			addErrorMessage("基础信息配置【利率模式】为空");
			return false;
		}
		if (StringUtils.isBlank($.getRate())) {
			addErrorMessage("营销信息配置【参考利率】为空");
			return false;
		}

		ProductJoinedLimit productJoinedLimit = $.getProductJoinedLimit();
		if (productJoinedLimit != null ){
			if (productJoinedLimit.getListLimit() != null || productJoinedLimit.getRecommendLimit() != null || productJoinedLimit.getTopicLimit() != null) {
				Integer totalJoinedLimit = 0;
				if (productJoinedLimit.getListLimit() != null) {
					totalJoinedLimit = totalJoinedLimit + productJoinedLimit.getListLimit();
				}

				if (productJoinedLimit.getRecommendLimit() != null) {
					totalJoinedLimit = totalJoinedLimit + productJoinedLimit.getRecommendLimit();
				}

				if (productJoinedLimit.getTopicLimit() != null) {
					totalJoinedLimit = totalJoinedLimit + productJoinedLimit.getTopicLimit();
				}

				if (!totalJoinedLimit.equals(100)) {
					addErrorMessage("控量信息加起来必须等于100，请重新输入。");
					return false;
				}
			}
		}

		return true;
	}

	public void onUploadBusinessLicense(FileUploadEvent event) {
		$.setBusinessLicense(this.uploadImg(event.getFile()));
	}

	public void onUploadLogo(FileUploadEvent event) {
		$.setLogo(this.uploadImg(event.getFile()));
	}

	public void onUploadMarketTag(FileUploadEvent event) {
		$.setMarketTag(this.uploadImg(event.getFile()));
	}

	public void onSelectAllProduct() {
		if (CollectionUtils.isEmpty($.getSelectedOnlineProducts()) || $.getSelectedOnlineProducts().size() < getCommProductIds().size()) {
			$.setSelectedOnlineProducts(getCommProductIds().stream().map(product -> product.getProductId().toString()).collect(Collectors.toList()));
		} else {
			$.getSelectedOnlineProducts().clear();
		}
	}

	public void onSelectAllExcludeChannel() {
		if (CollectionUtils.isEmpty($.getSelectedExcludeChannels()) || $.getSelectedExcludeChannels().size() < getCommProductChannels().size()) {
			$.setSelectedExcludeChannels(getCommProductChannels().stream().map(channel -> channel.getChannelCode().toString()).collect(Collectors.toList()));
		} else {
			$.getSelectedExcludeChannels().clear();
		}
	}

	@Override
	protected List<String> getDictionaryCodes() {
		return Lists.newArrayList(FIRST_PARTY_LOAN_TYPE, APPROVAL_TYPE, CREDIT_CARD_TAG, IDENTITY_TAG, LOAN_NECESSARY_DATA, PROMOTION_TYPE, RATE_TYPE, UNION_INFO, UNION_SERIAL,
				API_SERIAL, PLATFORM, THIRD_PARTY_LONG_TAG, LOAN_PRODUCT_REPAY_TYPE, LOAN_PRODUCT_TYPE, BLACK_LIST_TYPE, BLACK_LIST_TYPE, CUSTOMER_SERVICE_TYPE);
	}

	public void onAddTongdun() {
		selectTongdunManyHead = new ProductTongdunManyHead();
		tongdunIndustryList = new ArrayList<>();
		update("productInfoForm:tongdun-add-dialog");
	}

	public void onSeeTongdun(Integer rowIndex) {
		selectTongdunManyHead = tongdunManyHeads.get(rowIndex);
		tongdunIndustryList = Arrays.asList(selectTongdunManyHead.getIndustry().split(","));
		update("productInfoForm:tongdun-add-dialog");
	}

	public void onDeleteTongdun(Integer rowIndex) {
		ProductTongdunManyHead productTongdunManyHead = tongdunManyHeads.get(rowIndex);
		Long id = productTongdunManyHead.getId();
		if (id != null) {
			productTongdunManyHeadInfoService.delete(productTongdunManyHeadInfoService.findOne(id));
		}
		tongdunManyHeads.remove(productTongdunManyHead);
	}

	public void onSaveTongdun() {
		// 验证数据有效性
		boolean flag = validateTongdun();
		if (flag == false)
			return;
		// 添加
		String collect = tongdunIndustryList.stream().collect(Collectors.joining(","));
		selectTongdunManyHead.setIndustry(collect);
		if (!tongdunManyHeads.contains(selectTongdunManyHead)) {
			tongdunManyHeads.add(selectTongdunManyHead);
		}
		update("productInfoForm");
		addSuccessfullyMessage();
	}

	private boolean validateTongdun() {
		if (selectTongdunManyHead.getOnlyRemark() == null) {
			addErrorMessage("请选择唯一标识");
			return false;
		}
		if (selectTongdunManyHead.getTimeRemark() == null) {
			addErrorMessage("请选择时间");
			return false;
		}
		if (tongdunIndustryList == null || tongdunIndustryList.isEmpty()) {
			addErrorMessage("请选择行业");
			return false;
		}

		if (selectTongdunManyHead.getCounts() == null) {
			addErrorMessage("申请次数为空");
			return false;
		}
		return true;
	}

}
